package com.dzl.userwx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dzl.base.service.BaseServiceImpl;
import com.dzl.card.pojo.WelfareCardSecret;
import com.dzl.card.pojo.vo.WelfareUserCardSecretVo;
import com.dzl.card.service.WelfareCardSecretService;
import com.dzl.config.exception.CommonException;
import com.dzl.constant.CommonConstants;
import com.dzl.constant.WelfareCardEnum;
import com.dzl.constant.WelfareExchangeEnum;
import com.dzl.constant.WelfareOrderEnum;
import com.dzl.exchange.pojo.WelfareExchangeSecret;
import com.dzl.exchange.pojo.vo.ExchangeUserSecretVo;
import com.dzl.exchange.service.WelfareExchangeSecretService;
import com.dzl.order.pojo.WelfareOrder;
import com.dzl.order.service.WelfareOrderService;
import com.dzl.userwx.dao.WelfareUserWxMapper;
import com.dzl.userwx.pojo.WelfareUserWx;
import com.dzl.userwx.pojo.dto.UserWxIntegralDto;
import com.dzl.userwx.pojo.query.WelfareUserWxIdQuery;
import com.dzl.userwx.pojo.query.WelfareUserWxIntegralQuery;
import com.dzl.userwx.pojo.query.WelfareUserWxQuery;
import com.dzl.userwx.pojo.vo.UserWxIntegraDetaillVo;
import com.dzl.userwx.pojo.vo.WelfareUserCommonVo;
import com.dzl.userwx.pojo.vo.WelfareUserOrganizationVo;
import com.dzl.userwx.pojo.vo.WelfareUserWxVo;
import com.dzl.userwx.service.WelfareUserWxService;
import com.dzl.util.EmptyUtils;
import com.dzl.util.PasswordUtil;
import com.dzl.util.RedisUtil;
import com.dzl.util.TokenUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 小程序用户表(WelfareUserWx)表服务实现类
 * @author ChenLong
 * @since 2021-05-14 11:06:53
 */
@Slf4j
@Service("welfareUserWxService")
public class WelfareUserWxServiceImpl extends BaseServiceImpl<WelfareUserWx> implements WelfareUserWxService {

    @Autowired
    private WelfareUserWxMapper mapper;
    @Autowired
    private WelfareCardSecretService welfareCardSecretService;
    @Autowired
    private WelfareOrderService welfareOrderService;
    @Autowired
    private WelfareExchangeSecretService welfareExchangeSecretService;

    @Override
    public Map<String, Object> wxVerify(String openId) {
        Map<String, Object> mapRes = new HashMap<>();
        // 查询用户是否存在
        Example welfareUserWxExample = new Example(WelfareUserWx.class);
        welfareUserWxExample.createCriteria().andEqualTo("openId", openId);
        WelfareUserWx welfareUserWxResult = mapper.selectOneByExample(welfareUserWxExample);
        if (EmptyUtils.isEmpty(welfareUserWxResult)) {
            mapRes.put("code", 1011);
            mapRes.put("msg", "用户不存在");
            return mapRes;
        }
        // 校验是否绑卡
        Example welfareCardSecretExample = new Example(WelfareCardSecret.class);
        welfareCardSecretExample.createCriteria().andEqualTo("bindUserId", welfareUserWxResult.getId());
        List<WelfareCardSecret> welfareUserCardList = welfareCardSecretService.selectByExample(welfareCardSecretExample);
        if (EmptyUtils.isEmpty(welfareUserCardList) || welfareUserCardList.size() < 1) {
            mapRes.put("code", 1012);
            mapRes.put("msg", "用户未绑卡");
            return mapRes;
        }
        // 校验是否设置支付密码
        if (EmptyUtils.isEmpty(welfareUserWxResult.getPayPassword())) {
            mapRes.put("code", 1013);
            mapRes.put("msg", "未设置支付密码");
            return mapRes;
        }
        mapRes.put("code", 1);
        mapRes.put("msg", "success");
        return mapRes;
    }

    @Override
    public WelfareUserWx getWxUserInfo(String openId) {
        Example welfareUserWxExample = new Example(WelfareUserWx.class);
        welfareUserWxExample.createCriteria().andEqualTo("openId", openId);
        return mapper.selectOneByExample(welfareUserWxExample);
    }

    @Override
    public Integer getWxUserInfoEnterpriseId(String openId) {
        Example welfareUserWxExample = new Example(WelfareUserWx.class);
        welfareUserWxExample.createCriteria().andEqualTo("openId", openId).andNotEqualTo("enterpriseId",0);
        WelfareUserWx welfareUserWx = mapper.selectOneByExample(welfareUserWxExample);
        return EmptyUtils.isNotEmpty(welfareUserWx)?welfareUserWx.getEnterpriseId():null;
    }

    @Override
    public String login(Integer enterpriseId, String openid,String phone, String password) {
        WelfareUserWx query = new WelfareUserWx();
        query.setStatus(CommonConstants.YES);
        query.setEnterpriseId(enterpriseId);
        query.setPhone(phone);
        List<WelfareUserWx> list = mapper.select(query);
        WelfareUserWx welfareUserWx = EmptyUtils.isNotEmpty(list)?list.get(0):null;
        if(EmptyUtils.isEmpty(welfareUserWx)){
            throw new CommonException("您不是该企业员工");
        }
        if(!PasswordUtil.AESEncrypt(password).equals(welfareUserWx.getPassword())) {
            throw new CommonException("密码错误");
        }
        if(welfareUserWx.getIsValid()==CommonConstants.NO) {
            throw new CommonException("该手机号已停用");
        }
        if(EmptyUtils.isNotEmpty(welfareUserWx.getOpenId())){
            if(!welfareUserWx.getOpenId().equals(openid)){
                //更新用户openid
                welfareUserWx.setOpenId(openid);
                mapper.updateByPrimaryKeySelective(welfareUserWx);
            }
        }else{
            //更新用户openid
            welfareUserWx.setOpenId(openid);
            mapper.updateByPrimaryKeySelective(welfareUserWx);
        }
        //更新其他用户的openid设空值
        mapper.updateWxUserOpenid(welfareUserWx.getId(),openid);
        String token= TokenUtil.generateToken(welfareUserWx.getId());
        //删除之前的登录token
        Object oldToken=RedisUtil.get("userwx:"+welfareUserWx.getId());
        if(EmptyUtils.isNotEmpty(oldToken)){
            RedisUtil.delete(oldToken.toString());
        }
        //保存token到redis
        RedisUtil.set(token, JSON.toJSONString(welfareUserWx) ,60*60*24*3);//缓存3天
        //保存用户最新token到redis //缓存7天
        RedisUtil.set("userwx:"+welfareUserWx.getId(), token ,60*60*24*3);
        return token;
    }

    @Override
    public WelfareUserCommonVo getWxUserCommonInfo(Integer userId) {
        WelfareUserCommonVo welfareUserCommonVo = new WelfareUserCommonVo();
        // 获取绑卡数量
        Example WelfareCardSecretExample = new Example(WelfareCardSecret.class);
        WelfareCardSecretExample.createCriteria()
                .andEqualTo("status", CommonConstants.YES)
                .andGreaterThan("expiredDate", new Date())
                .andEqualTo("isActivate", WelfareCardEnum.CARD_SECRET_ACTIVE_STATUS_BOUND.getCode())
                .andGreaterThan("remainAmount", 0)
                .andEqualTo("bindUserId", userId);
        Integer cardQuantity = welfareCardSecretService.selectCountByExample(WelfareCardSecretExample);
        // 获取绑定兑换券数量
        Example exchangeSecretDetailsExample = new Example(WelfareExchangeSecret.class);
        exchangeSecretDetailsExample.createCriteria()
                .andEqualTo("status", CommonConstants.YES)
                .andGreaterThan("expiredDate", new Date())
                .andEqualTo("isActivate", WelfareExchangeEnum.EXCHANGE_SECRET_ACTIVE_STATUS_BOUND.getCode())
                .andEqualTo("bindUserId", userId);
        Integer exchangeQuantity = welfareExchangeSecretService.selectCountByExample(exchangeSecretDetailsExample);
        // 获取正在进行订单数量
        List<Integer> integerList = new ArrayList<>();
        integerList.add(WelfareOrderEnum.ORDER_STATUS_COMPLETED.getCode());
        integerList.add(WelfareOrderEnum.ORDER_STATUS_CANCEL.getCode());
        integerList.add(WelfareOrderEnum.ORDER_STATUS_NO_DELIVERY_REFUND.getCode());
        integerList.add(WelfareOrderEnum.ORDER_STATUS_DELIVERY_REFUND.getCode());
        Example welfareOrderExample = new Example(WelfareOrder.class);
        welfareOrderExample.createCriteria()
                .andEqualTo("status", 1)
                .andEqualTo("userId", userId)
                .andNotIn("orderStatus", integerList);
        Integer orderQuantity = welfareOrderService.selectCountByExample(welfareOrderExample);
        welfareUserCommonVo.setUserId(userId);
        welfareUserCommonVo.setCardQuantity(cardQuantity);
        welfareUserCommonVo.setExchangeQuantity(exchangeQuantity);
        welfareUserCommonVo.setOrderQuantity(orderQuantity);
        return welfareUserCommonVo;
    }

    @Override
    public Integer addPayPassword(Integer userId, String ppwd) {
        return mapper.updatePayPassword(userId, PasswordUtil.AESEncrypt(ppwd));
    }

    @Override
    public Integer updatePayPassword(Integer userId, String ppwd) {
        return this.mapper.updatePayPassword(userId, PasswordUtil.AESEncrypt(ppwd));
    }

    @Override
    public Integer updatePhoneNumber(Integer userId, String phoneNumber) {
        return this.mapper.updatePhoneNumber(userId, phoneNumber);
    }

    @Override
    public PageInfo<WelfareUserWxVo> selectUserWxListPage(WelfareUserWxQuery query) {
        PageHelper.startPage(query);
        List<WelfareUserWxVo> list = mapper.selectUserWxListPage(query);
        PageInfo<WelfareUserWxVo> page = new PageInfo<WelfareUserWxVo>(list);
        return page;
    }

    @Override
    public Map<String, Object> getWxUserInfoByIdAll(Integer id) {
        //获取用户基本信息
        WelfareUserWxVo welfareUserWxVo = mapper.selectUserWxVoById(id);
        //获取用户卡信息
        List<WelfareUserCardSecretVo> welfareUserCardSecretVoList = welfareCardSecretService.selectUserCardSecretVoListByUserId(id);
        //获取用户兑换券信息
        List<ExchangeUserSecretVo> exchangeUserSecretVoList = welfareExchangeSecretService.selectUserExchangeSecretVoListByUserId(id);
        //获取用户订单信息
        //List<WelfareOrderVo> welfareOrderVoList = welfareOrderService.selectWelfareOrderVoListByUserId(id);
        Map<String, Object> map = new HashMap<>();
        map.put("welfareUserWxVo", welfareUserWxVo);
        map.put("welfareUserCardSecretVoList", welfareUserCardSecretVoList);
        map.put("exchangeUserSecretVoList", exchangeUserSecretVoList);
        //map.put("welfareOrderVoList", welfareOrderVoList);
        return map;
    }

    @Override
    public WelfareUserWxVo getWxUserInfoById(Integer id) {
        return mapper.selectUserWxVoById(id);
    }

    @Override
    public List<WelfareUserCardSecretVo> getUserWxCardInfoById(Integer id) {
        return welfareCardSecretService.selectUserCardSecretVoListByUserId(id);
    }

    @Override
    public List<WelfareUserCardSecretVo> getUserWxCardInfoListNoExpiredById(Integer userId, Integer cardSecretId, Integer notIncludedCardSecretId) {
        return welfareCardSecretService.getUserWxCardInfoListNoExpiredById(userId, cardSecretId, notIncludedCardSecretId);
    }

    @Override
    public Integer updateUserIntegral(List<Integer> userIdList, BigDecimal integral) {
        return mapper.updateUserIntegral(userIdList, integral);
    }

    @Override
    public List<WelfareUserOrganizationVo> getUserWxIntegralPage(WelfareUserWxIntegralQuery query) {
        if(EmptyUtils.isNotEmpty(query.getOrganizationIds())) {
            List<Integer> organizationIds = Arrays.stream(query.getOrganizationIds().split(",")).map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList()) ;
            int length = organizationIds.size();
            int lastOrganizationId = organizationIds.get(length-1);
            query.setLastOrganizationId(lastOrganizationId);
            query.setOrganizationLevel(length);
        }
        PageHelper.startPage(query);
        List<WelfareUserOrganizationVo> list = mapper.selectUserWxIntegralPage(query);
        if(EmptyUtils.isNotEmpty(list)) {
            list.forEach(x -> {
                String organizationName = "";
                if(EmptyUtils.isNotEmpty(x.getFirstOrganizationName())) {
                    organizationName = organizationName + x.getFirstOrganizationName();
                }
                if(EmptyUtils.isNotEmpty(x.getSecondOrganizationName())) {
                    organizationName = organizationName + "/" + x.getSecondOrganizationName();
                }
                if(EmptyUtils.isNotEmpty(x.getThirdOrganizationName())) {
                    organizationName = organizationName + "/" + x.getThirdOrganizationName();
                }
                if(EmptyUtils.isNotEmpty(x.getFourthOrganizationName())) {
                    organizationName = organizationName + "/" + x.getFourthOrganizationName();
                }
                if(EmptyUtils.isNotEmpty(x.getFifthOrganizationName())) {
                    organizationName = organizationName + "/" + x.getFifthOrganizationName();
                }
                x.setOrganizationName(organizationName);
            });
        }
        return list;
    }

    @Override
    public List<WelfareUserOrganizationVo> getOrganizationUser(WelfareUserWxIntegralQuery query) {
        List<WelfareUserOrganizationVo> list = mapper.selectOrganizationUser(query);
        if(EmptyUtils.isNotEmpty(list)) {
            list.forEach(x -> {
                String organizationName = "";
                String organizationIdStr = "";
                if(EmptyUtils.isNotEmpty(x.getFirstOrganizationName())) {
                    organizationName = organizationName + x.getFirstOrganizationName();
                    organizationIdStr = organizationIdStr + x.getFifthOrganizationId();
                }
                if(EmptyUtils.isNotEmpty(x.getSecondOrganizationName())) {
                    organizationName = organizationName + "/" + x.getSecondOrganizationName();
                    organizationIdStr = organizationIdStr + "/" + x.getSecondOrganizationId();
                }
                if(EmptyUtils.isNotEmpty(x.getThirdOrganizationName())) {
                    organizationName = organizationName + "/" + x.getThirdOrganizationName();
                    organizationIdStr = organizationIdStr + "/" + x.getThirdOrganizationId();
                }
                if(EmptyUtils.isNotEmpty(x.getFourthOrganizationName())) {
                    organizationName = organizationName + "/" + x.getFourthOrganizationName();
                    organizationIdStr = organizationIdStr + "/" + x.getFourthOrganizationId();
                }
                if(EmptyUtils.isNotEmpty(x.getFifthOrganizationName())) {
                    organizationName = organizationName + "/" + x.getFifthOrganizationName();
                    organizationIdStr = organizationIdStr + "/" + x.getFifthOrganizationId();
                }
                x.setOrganizationName(organizationName);
                x.setOrganizationIdStr(organizationIdStr);
            });
        }
        return list;
    }

    @Override
    public List<UserWxIntegraDetaillVo> getUserIntegralDetail(WelfareUserWxIdQuery query) {
        PageHelper.startPage(query);
        return mapper.getUserIntegralDetail(query);
    }

    @Override
    public Integer updateIntegralForExpired(UserWxIntegralDto dto) {
        return mapper.updateIntegralForExpired(dto);
    }

}
